#include "httpinfo.h"
/**********************************
 * 返回关于响应文件信息的http头部
 * 输入：
 * client_sock 客户端socket句柄
 * resource  文件的句柄
 * *****************************/
int headers(int client_sock, FILE* resource)
{
	struct stat st;
	int fileid=0;
	char buf[1024]={0};
	char tmp[64];
	strcpy(buf, "HTTP/1.0 200 OK\r\n");
	strcat(buf, "Server: My Server\r\n");
	strcat(buf, "Content-Type: text/html\r\n");
	strcat(buf, "Connection: Close\r\n");

	fileid=fileno(resource);
	if(fstat(fileid, &st)==-1)
	{
		innerError(client_sock);
		return -1;
	}
	snprintf(tmp, 64, "Content_length:%d\r\n\r\n", st.st_size);
	strcat(buf, tmp);
	if(debug)	fprintf(stdout, "header: %s\n", buf);
	if(send(client_sock, buf, strlen(buf), 0) < 0)
	{
		fprintf(stderr, "send failed. data: %s, reason:%s\n", buf, strerror(errno));
		return -1;
	}
	return 0;
}
void cat(int client_sock, FILE* resource)//将html文件的内容按行读取并送给客户端
{
	char buf[1024];
	fgets(buf, sizeof(buf), resource);

	while(!feof(resource))
	{
		int len=write(client_sock, buf, strlen(buf));
		if(len<0)//发送body的过程中出现问题，1、重试
		{
			fprintf(stderr, "send body error. reason: %s\n", strerror(errno));
			break;
		}
		if(debug)	fprintf(stdout, "%s", buf);
		fgets(buf, sizeof(resource), resource);
	}
}